package com.study.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

//国际化
@Configuration
public class MyLocalResovel implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String lang = httpServletRequest.getParameter("l");
        String header = httpServletRequest.getHeader("Accept-Language");

        Locale locale =null;
        if (!StringUtils.isEmpty(lang)){
            String[] split = lang.split("_");//  zh_CN =>  {“zh”,"CN"}
            locale = new Locale(split[0], split[1]);//Ctrl +p查看方法参数
            //split[0]   =>“zh”
            //split[1]   =>“CN”

        }else {
            String[] split = header.split(",");
            String[] split1 = split[0].split("-");
            locale = new Locale(split1[0], split1[1]);
        }


        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }

    @Bean
    public LocaleResolver localeResolver(){

        return new MyLocalResovel();
    }
}
